package com.todo.service.impl;


import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.todo.constant.JwtClaimsConstant;
import com.todo.dto.LoginFormDTO;
import com.todo.dto.Result;
import com.todo.dto.UpdatePasswordDTO;
import com.todo.dto.UserDTO;
import com.todo.entity.User;
import com.todo.entity.UserInfo;
import com.todo.mapper.UserInfoMapper;
import com.todo.mapper.UserMapper;
import com.todo.properties.JwtProperties;
import com.todo.service.IUserService;
import com.todo.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author carol
 * @since 2023-09-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    UserInfoMapper userInfoMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private UIDUtil uidUtil;

    @Resource
    private JwtProperties jwtProperties;

    @Resource
    private UserMapper userMapper;
    /**
     * 发送验证码
     * @param phone
     * @param session
     * @return
     */
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.校验手机号（正则表达式）
        if (RegexUtils.isPhoneInvalid(phone)){
            //2.不符合返回错误信息
            return Result.fail("手机号格式错误！");
        }
        //3.符合，生成验证码
        String code = RandomUtil.randomNumbers(6);
        //4.保存验证码到Redis
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY + phone,code,RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);
        session.setAttribute("code",code);
        //5. 发送验证码
        log.info("发送短信验证码成功：{}",code);
        //6.返回ok
        return Result.ok();
    }

    /**
     * 登录功能 返回token
     * @param loginForm
     * @return
     */
    @Override
    public Result login(LoginFormDTO loginForm) {
        //1.手机号+验证码登录
        if (loginForm.getPhone()!=null && loginForm.getCode()!=null){
            return loginThroughPhoneAndCode(loginForm);
        }else if (loginForm.getPhone()!=null ){
            return loginThroughPhoneAndPassword(loginForm);
        }else if (loginForm.getUid()!= null){
            return loginThroughUIDAndPassword(loginForm);
        }
        return Result.fail("登录失败");
    }

    /**
     * 传入User对象修改密码
     * @param user
     * @return
     */
    @Override
    public Result savePassword(User user) {
        String uid = UserHolder.getUser().getUid();
        user.setUid(uid);
        if (user.getUPassword()!=null && !user.getUPassword().equals("")){
            //密码加密
            String password = MD5Encoder.encode((user.getUPassword()+"carol").getBytes());
            UpdateWrapper<Object> updateWrapper = Wrappers.update();
            updateWrapper.set("u_password",password);
            UpdateWrapper<Object> objectUpdateWrapper = updateWrapper.eq("uid", uid);
            return Result.ok("修改密码返回结果："+ objectUpdateWrapper.toString());
        }
        return Result.fail("传入密码为空");
    }

    /**
     * 通过uid获取userDTO
     * @param uid
     * @return
     */
    @Override
    public UserDTO getMyInfo(String uid) {
        User user = userMapper.selectByUid(uid);
        log.info("我的信息uid：{}",user);
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user,userDTO);//第一个参数是有数据的，将第一个参数的数据填入第二个参数
        return userDTO;
    }

    @Override
    public Result updatePassword(UpdatePasswordDTO updatePasswordDTO) {
        //获取当前操作的用户uid
        String uid = UserHolder.getUser().getUid();
        //获取数据库中的user对象
        User userDB = userMapper.selectByUid(uid);
        if (ObjectUtils.isEmpty(userDB)){
            return Result.fail("当前用户未登录");
        }
        
        return null;
    }

    /**
     * 通过UID与密码进行登录
     * @param loginForm
     * @return
     */
    private Result loginThroughUIDAndPassword(LoginFormDTO loginForm) {
        //1.1获取手机号 密码
        String uid = loginForm.getUid();
        String password = loginForm.getPassword();

        //2.判断uid是否存在
        User user = userMapper.selectByUid(uid);
        if (ObjectUtils.isEmpty(user)){
            //2.1uid不存在返回错误信息
            return Result.fail("uid不存在");
        }
        //3.判断密码是否正确
        //3.1查询数据库中对应用户的密码
        String passwordDB = user.getUPassword();
        //3.2密码md5加密后判断
        password = MD5Encoder.encode((password+"carol").getBytes(StandardCharsets.UTF_8));
        if (!passwordDB.equals(password)){
            //3.2.1密码错误，返回错误信息
            return Result.fail("登陆失败，密码错误");
        }
        //4.登录成功，生成token
        String token = getToken(user);
        //4.1 token保存入redis

        //将user保存放入线程
        saveUser(user);

        //5返回token
        return Result.ok(token);
    }

    /**
     * 通过手机号与密码进行登录
     * @param loginForm
     * @return
     */
    private Result loginThroughPhoneAndPassword(LoginFormDTO loginForm) {
        //1.1获取手机号 密码
        String phone = loginForm.getPhone();
        String password = loginForm.getPassword();
        //1.2判断手机号是否合法
        if (RegexUtils.isPhoneInvalid(phone)){
            //1.2不符合返回错误信息
            return Result.fail("手机号格式错误！");
        }
        //2.判断手机号是否存在
        User user = query().eq("u_phone", phone).one();
        if (ObjectUtils.isEmpty(user)){
            //2.1手机号不存在，返回错误信息
            return Result.fail("手机号码不存在");
        }
        //3.判断密码是否正确
        //3.1查询数据库中对应用户的密码
        String passwordDB = user.getUPassword();
        //3.2密码md5加密后判断
        password = MD5Encoder.encode((password+"carol").getBytes(StandardCharsets.UTF_8));
        if (!passwordDB.equals(password)){
            //3.2.1密码错误，返回错误信息
            return Result.fail("登陆失败，密码错误");
        }
        //将user保存放入线程
        saveUser(user);
        //4.登录成功，生成token
        String token = getToken(user);
        //5返回token
        return Result.ok(token);
    }

    /**
     * 通过手机号与验证码登录
     * @param loginForm
     * @return
     */
    private Result loginThroughPhoneAndCode(LoginFormDTO loginForm){
        //1.1校验手机号和验证码
        String phone = loginForm.getPhone();

        if (RegexUtils.isPhoneInvalid(phone)){
            //1.2不符合返回错误信息
            return Result.fail("手机号格式错误！");
        }
        //2.校验验证码 从redis获取
        String cacheCode = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + phone);
        String code = loginForm.getCode();
        if (cacheCode == null || !cacheCode.toString().equals(code)){
            //3.不一致 报错
            return Result.fail("验证码错误");
        }
        //4.一致，根据手机号查询数据库 select * from tb_user where phone = ?
        //使用mybatis plus
        User user = query().eq("u_phone", phone).one();

        //5.判断是否存在
        if (user == null){
            //6.不存在。创建新用户
            user = createUserWithPhone(phone);
        }
        //7.存在，生成token并保存用户信息到redis
        //String token = createAndSaveToken(user);
        String token = getToken(user);
        /*//7.1生成token作为登录令牌 UUID生成token
        String token = UUID.randomUUID().toString(true);

        //7.2将User对象转为Hash储存
        //7.3储存
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user,userDTO);//后面是填入的对象
        //userDTO转map
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,new HashMap<>(), CopyOptions.create()
                .setIgnoreNullValue(true)
                .setFieldValueEditor((fieldName,fieldValue)->fieldValue.toString()));
        stringRedisTemplate.opsForHash().putAll(RedisConstants.LOGIN_USER_KEY+token,userMap);
        //设置有效期
        stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY+token,RedisConstants.LOGIN_USER_TTL,TimeUnit.MINUTES);*/
        //将user保存放入线程
        saveUser(user);
        //8.返回token
        //没有访问超过三十分钟再过期，不断地访问就不断更新
        return Result.ok(token);
    }

    private void saveUser(User user){
        UserDTO userDTO = new UserDTO();
        //后面的是空对象，需要填入数据的对象
        BeanUtils.copyProperties(user,userDTO);
        UserHolder.saveUser(userDTO);
    }

    /**
     * 生成用户token并将用户信息保存到redis
     * @param user
     * @return
     */
    /*private String createAndSaveToken(User user){

        //7.存在，保存用户信息到redis
        //7.1生成token作为登录令牌 UUID生成token
        String token = UUID.randomUUID().toString(true);
        //7.2将User对象转为Hash储存
        //7.3储存
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user,userDTO);//后面是填入的对象
        //userDTO转map
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,new HashMap<>(), CopyOptions.create()
                .setIgnoreNullValue(true)
                .setFieldValueEditor((fieldName,fieldValue)->fieldValue.toString()));
        stringRedisTemplate.opsForHash().putAll(RedisConstants.LOGIN_USER_KEY+token,userMap);
        //设置有效期
        stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY+token,RedisConstants.LOGIN_USER_TTL,TimeUnit.MINUTES);
        return token;
    }
*/
    private String getToken(User user){
        Map<String,Object> climes = new HashMap<>();
        //将userId存入localThread
        climes.put(JwtClaimsConstant.USER_UID, user.getUid());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), climes);
        log.info("userService获取Token:{}",token);
        return token;
    }


    /**
     * 通过手机号码创建新用户
     * @param phone
     * @return
     */
    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setUPhone(phone);
        //用户昵称初始为随机字符串
        user.setUName(SystemConstants.USER_NICK_NAME_PREFIX+RandomUtil.randomString(10));
        //设置用户十位UID
        String uid = uidUtil.getUID();
        user.setUid(uid);
        LocalDateTime now = LocalDateTime.now();
        user.setCreateTime(now);
        user.setUpdateTime(now);
        //创建用户详细信息对象，并初始化
        UserInfo userInfo = new UserInfo();
        userInfo.setUid(uid);
        userInfo.setCreateTime(now);
        userInfo.setUpdateTime(now);
        userInfoMapper.insert(userInfo);
        save(user);
        return user;
    }
}
